package ptu.dao;

import org.apache.ibatis.annotations.*;
import ptu.entity.Book;
import ptu.entity.Records;
import ptu.entity.User;
import ptu.entity.vo.RecordsVo;

import java.util.List;

@Mapper
public interface RecordsDao {

    @Select("select * from records")
    List<Records> selectAll();

    @Select("select * from records where b_id =#{bId} and u_id=#{uId}")
    Records selectByBIdAndByUId(@Param("bId") Integer bId,@Param("uId") Integer uId);


    //通过图书Id查询图书被谁借走
    @Select("SELECT u.id,u.username,u.`password`,u.amount from `user` u,(SELECT u_id FROM records WHERE b_id=#{bId}) a WHERE u.id=a.u_id;")
    List<User> selectByBId(Integer bId);

    //通过用户id查询用户目前借了那些书
    @Select("SELECT b.id,b.b_name,b.b_price,b.b_time,b.b_size,b.b_author,b.b_press from book b,(SELECT b_id FROM records WHERE u_id=#{uId}) a WHERE  b.id=a.b_id;")
    List<Book> selectByUId(Integer uId);

    @Insert("insert into records values(DEFAULT,#{bId},#{uId},#{borrowTime},null)")
    int insert(Records records);

    @Update("update records set return_time=#{returnTime} where b_id=#{bId} and u_id=#{uId}")
    int update(Records records);

    @Select("SELECT r.id,b.b_name as bookName,u.username,r.borrow_time,r.return_time\n" +
            "        FROM records r\n" +
            "        LEFT JOIN user u ON (r.u_id=u.id)\n" +
            "        LEFT JOIN book b ON (r.b_id=b.id)" +
            "        WHERE u.username=#{username} and r.return_time is null")
    List<RecordsVo> selectByUsername(String username);

    @Select("SELECT r.id,b.b_name as bookName,u.username,r.borrow_time,r.return_time\n" +
            "        FROM records r\n" +
            "        LEFT JOIN user u ON (r.u_id=u.id)\n" +
            "        LEFT JOIN book b ON (r.b_id=b.id)" )
    List<RecordsVo> selectAllRecord();

//    我借过哪些书？还没还的
    @Select("SELECT\n" +
            "\tb.* \n" +
            "FROM\n" +
            "\trecords r\n" +
            "\tLEFT JOIN book b ON r.b_id = b.id \n" +
            "WHERE\n" +
            "\tr.u_id =#{id} AND r.return_time is NULL")
    List<Book> selectByUserId(Integer id);
}
